<template>
  <div class="edit-down-modal">
    <el-input class="edit-down-input" v-model="row[column.field]" :title="row[column.field]" placeholder="请选择" @click="popupEvent">
      <template #suffix>
        <el-link class="edit-popup-button" type="primary" :underline="false" @click="popupEvent">
          获取
        </el-link>
      </template>
    </el-input>
    <el-drawer
      v-model="modalVisible"
      direction="rtl"
      size="800"
      :append-to-body="true"
    >
      <template #header>
        <h4>请选择</h4>
      </template>
      <template #default>
        <div class="drawer-body-lock">
          <el-space :size="20" style="margin-bottom: var(--main-padding);">
            <span>是否为数组</span>
            <el-switch
              v-model="dataType"
              style="--el-switch-off-color: #909399"
              :active-value="RecordTypeEnum.Array"
              :inactive-value="RecordTypeEnum.Base"
              :active-icon="Check"
              inline-prompt
              @change="dateTypeChange"
            />
            <span v-if="dataType !== RecordTypeEnum.Base">参数连接符</span>
            <el-input v-if="dataType !== RecordTypeEnum.Base" v-model="separator" />
          </el-space>
          <el-row :gutter="24">
            <el-col :span="16">
              <el-form-item>
                <el-radio-group v-model="fieldType" @change="typeChange">
                  <el-radio value="base">基本类型</el-radio>
                  <el-radio value="enum">数据结构（枚举）</el-radio>
                  <el-radio value="class">数据结构（类）</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-input v-model="searchKey" placeholder="请输入搜索内容" class="csc-search-input" clearable @change="searchEvent">
                <template #append>
                  <el-button :icon="Search" @change="searchEvent" />
                </template>
              </el-input>
            </el-col>
          </el-row>

          <div class="drawertable-content">
            <vxe-grid class="drawer-grid" highlight-hover-row auto-resize show-overflow ref="typeTreeTable" height="auto" border="none" :loading="loading" :data="list" :radio-config="{ highlight: true, trigger: 'row' }" :columns="tableColumn">
            </vxe-grid>
          </div>
        </div>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button plain @click="modalVisible = false">取 消</el-button>
          <el-button :loading="loading" type="primary" @click="confirmEvent">确 定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { searchStructDataApi } from "@@/apis/basic-data/index";
import { listDatatype } from "@@/apis/basic-type/index";
import { BasicClassValueField, BSTableData, PageTableRequestData } from "@@/apis/basic-data/types";
import { BSDataTypeEnum, RecordTypeEnum } from "@@/constants/other-keys";
import { cloneDeep } from "lodash";
import { ref, nextTick } from "vue";
import { VxeGlobalRendererHandles } from "vxe-pc-ui";
import { VxeGridPropTypes, VxeTableDefines } from "vxe-table";
import XEUtils from "xe-utils";
import { BasicTypeInfo } from "@@/apis/basic-type/types";
import { Search, Check } from "@element-plus/icons-vue"

interface Props {
  params: VxeGlobalRendererHandles.RenderTableEditParams
}

const props = defineProps<Props>()
const typeTreeTable = ref();
const fieldType = ref<BSDataTypeEnum>(BSDataTypeEnum.Base)
const separator = ref<string>(";")
const row = ref<BasicClassValueField>(props.params.row)
const column = ref<VxeTableDefines.ColumnInfo>(props.params.column)
const modalVisible = ref<boolean>(false)
const loading = ref<boolean>(false)
const searchKey = ref<string>()
const tableData = ref<BSTableData[] | BasicTypeInfo[]>([])
const list = ref<BSTableData[] | BasicTypeInfo[]>([])
const baseDatas = ref<BasicTypeInfo[]>([])
const structData = ref<BSTableData[]>([])
const tableColumn = ref<VxeGridPropTypes.Columns>([])
const structColumn = ref<VxeGridPropTypes.Columns>([
  { type: 'radio', width: 60 },
  { field: 'id', title: '标识', visible: false },
  { field: 'code', title: '标识', align: "left" },
  { field: 'name', title: '辅助标识', align: "left" },
  { field: 'description', title: '描述', showOverflow: true, align: "left" }
])
const baseColumn = ref<VxeGridPropTypes.Columns>([
  { type: 'radio', width: 60 },
  { field: 'id', title: '标识', visible: false },
  { field: 'value', title: '标识' },
  { field: 'label', title: '辅助标识' },
])
const dataType = ref<RecordTypeEnum>(RecordTypeEnum.Base)

const getBaseDatas = () => {
  return new Promise((resolve) => {
    listDatatype({}).then(({ data }) => {
      baseDatas.value = data;
      tableData.value = cloneDeep(baseDatas.value);
      resolve(data)
    })
  })
}
const dateTypeChange = () => {
  if (dataType.value == RecordTypeEnum.Array) {
    separator.value = ';';
  }
}
const typeChange = async (_type: BSDataTypeEnum) => {
  switch (_type) {
    case BSDataTypeEnum.Base:
      await getBaseDatas();
      tableColumn.value = cloneDeep(baseColumn.value);
      tableData.value = cloneDeep(baseDatas.value);
      break;
    case BSDataTypeEnum.Enum:
      await getStructDataPromise();
      tableColumn.value = cloneDeep(structColumn.value);
      tableData.value = structData.value;
      typeTreeTable.value.loadData(tableData.value);
      break;
    case BSDataTypeEnum.Class:
      await getStructDataPromise();
      tableColumn.value = cloneDeep(structColumn.value);
      tableData.value = structData.value;
      typeTreeTable.value.loadData(tableData.value);
  }
  handleSearch()
  nextTick(() => {
    let currentRow = XEUtils.find(tableData.value, item => item.id == row.value.typeId);
    currentRow && typeTreeTable.value && typeTreeTable.value.setRadioRow(currentRow);
  })
}

const getStructDataPromise = (): Promise<BSTableData[]> => {
  return new Promise(resolve => {
    const params : PageTableRequestData = {
      type: fieldType.value,
      code: searchKey.value
    }
    searchStructDataApi(params).then(({ data }) => {
      structData.value = data.rows
      resolve(data.rows)
    }).catch(() => {
      structData.value = []
      resolve([])
    })
  })
}
const popupEvent = () => {
  modalVisible.value = true;
  nextTick(() => {
    if (row.value.type) {
      fieldType.value = row.value.type;
      dataType.value = row.value.recordType;
      separator.value = row.value.separator;
      typeChange(fieldType.value);
    }
  })
}
const confirmEvent = () => {
  const selectRecord = typeTreeTable.value.getRadioRecord()
  if (selectRecord != null) {
    row.value.type = fieldType.value;
    row.value[column.value.field] = (fieldType.value !== BSDataTypeEnum.Base ? selectRecord.code : selectRecord.value);
    if (dataType.value == RecordTypeEnum.Array) {
      row.value[column.value.field] = "DA_" + row.value[column.value.field];
      row.value.separator = separator.value;
    }
    row.value.typeId = selectRecord.id;
    row.value.recordType = dataType.value;
  }
  modalVisible.value = false
}

const handleSearch = () => {
  if (searchKey.value != undefined) {
    const filterVal = String(searchKey.value).trim().toLowerCase()
    let searchProps: string[] = []
    if (fieldType.value == BSDataTypeEnum.Base) {
      searchProps = ['value', 'label']
    } else {
      searchProps = ['name', 'code', 'description', 'value', 'label']
    }
    const rest = tableData.value.filter(item => searchProps.some(key => String(item[key]).toLowerCase().indexOf(filterVal) > -1))
    list.value = rest.map(row => {
      // 搜索为克隆数据，不会污染源数据
      const item = XEUtils.clone(row)
      return item
    })
  } else {
    list.value = tableData.value
  }
}

const searchEvent = XEUtils.throttle(function () {
  handleSearch()
}, 500, { trailing: true, leading: true })

searchKey.value = undefined
tableColumn.value = baseColumn.value;
typeChange(fieldType.value);
</script>

<style lang="scss" scoped>
.edit-down-modal {
  display: flex;
  align-items: center;
}

.edit-popup-button {
  width: 60px;
}

.edit-down-pulldown {
  width: auto;
  flex-grow: 1;
}

:deep(.edit-down-input .vxe-input--inner) {
  border-radius: 4px 0 0 4px;
}

.mytable-scrollbar .vxe-radio--label {
  display: block;
}

.footerDiv {
  margin-top: 5px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  span {
    width: 80px;
    color: #ffffff;
  }

  &.start {
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }

  .left {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    :deep(.vxe-input--inner) {
      color: #ffffff;
      border: 1px solid #266ca7;
      background-color: #0b1b32;
    }
  }
}
</style>
